package com.haoshuang.zhouzhoubang.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.haoshuang.zhouzhoubang.databinding.ActivityAddMemberBinding
import com.haoshuang.zhouzhoubang.model.bean.GroupBean
import com.haoshuang.zhouzhoubang.ui.adapter.AddMemberAdapter
import com.haoshuang.zhouzhoubang.ui.vm.AddMemberViewModel
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical


/**
 *
 */
class AddMemberActivity : BaseVMActivity<AddMemberViewModel, ActivityAddMemberBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<AddMemberActivity>()
        }
    }

    private var idList = arrayListOf<String>()

    private val data = arrayListOf<GroupBean.AllPeople>()
    private val adapter = AddMemberAdapter(data)

    override fun initView(savedInstanceState: Bundle?) {

        val ids = intent.getString("ids")
        idList.clear()
        idList.addAll(ids.split(",").filter { it.isNotEmpty() })

        binding.titleBar.title = "分组管理"
        binding.titleBar.leftImageView().click { finish() }

        binding.recyclerView.vertical()
            .adapter = adapter

        adapter.setOnItemClick { view, position , item->
            val item = adapter.getItem(position)
            if (item?.isCHeck2 == 1){
                toast("已存在的成员, 无法取消")
                return@setOnItemClick
            }

            data[position].isCHeck = if (data[position].isCHeck == 1) 0 else 1
            adapter.notifyDataSetChanged()
        }

        binding.tvAdd.clickWithTrigger {
            val list = data.filter { it.isCHeck == 1 }
            if (list.isEmpty()){
                toast("请选择成员")
                return@clickWithTrigger
            }
            val ids = list.joinToString(","){it.uid.toString()}
            setResult(200, Intent().apply { putExtra("ids", ids) })
            finish()
        }

    }

    override fun initData() {
        vm.getTeamMemberList()
    }

    override fun startObserve() {
        vm.getTeamMemberListData.observeState(this){
            onLoading {showLoading()}
            onError {code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                data.clear()
                data.addAll(it?: emptyList())
                for (datum in data) {
                    if (datum.uid.toString() in idList){
                        datum.isCHeck = 1
                        datum.isCHeck2 = 1
                    }
                }
                adapter.notifyDataSetChanged()
            }
        }
    }

}